﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Dropthings.Widget.Widgets;
using Dropthings.Widget.Framework;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;

public partial class Widgets_SLDataGridWidget : System.Web.UI.UserControl, IWidget

{

    string strResult;
    public string ColumnValue = "";
    public string DataValue = "";

    private IWidgetHost _Host;

    private XElement _State;
    private XElement State
    {
        get
        {
            string state = this._Host.GetState();
            if (string.IsNullOrEmpty(state))
                state = "<state><strPoshCode></strPoshCode><strHtmlRender></strHtmlRender><refresh>false</refresh></state>";
            if (_State == null) _State = XElement.Parse(state);
            return _State;
        }
    }

    public bool Refresh
    {
        get { return bool.Parse((State.Element("refresh") ?? new XElement("refresh", "false")).Value); }
        set
        {
            if (State.Element("refresh") != null) State.Element("refresh").Value = value.ToString();
            else State.Add(new XElement("refresh", value.ToString()));
        }
    }

    public string strPoshCode
    {
        get { return (State.Element("strPoshCode") ?? new XElement("strPoshCode", "")).Value; }
        set { State.Element("strPoshCode").Value = value; }
    }

    public string strHtmlRender
    {
        get { return (State.Element("strHtmlRender") ?? new XElement("strHtmlRender", "")).Value; }
        set { State.Element("strHtmlRender").Value = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader objReader = new StreamReader(Server.MapPath("~/PowerShell/FormatGrid.ps1"));
        string strAddScript = objReader.ReadToEnd();
        
        if (Session["Refresher"] != null)
        {
            string strTraceSession = Session["Refresher"].ToString();
            string[] strSplittedArgs = strTraceSession.Split(';');            
            strPoshCode = strAddScript + strPoshCode;
            
            // Update the script with refresher
            strPoshCode = strPoshCode.Replace(strSplittedArgs[0], strSplittedArgs[1]);
            this.executePowerShellCode(strPoshCode);
            this.strHtmlRender = strResult;
        }
        else if (Request.Params["Refresh"] == "yes")
        {            
            strPoshCode = strAddScript + strPoshCode;
            this.executePowerShellCode(strPoshCode);
            this.strHtmlRender = strResult;
            this.State.Add(new XCData(strResult));
            this.SaveState();
        }
    }

    void IWidget.Init(IWidgetHost host)
    {
        this._Host = host;
    }

    void IWidget.ShowSettings()
    {
        PoshtextBox.Text = this.strPoshCode;
        SettingsPanel.Visible = true;
    }
    void IWidget.HideSettings()
    {
        SettingsPanel.Visible = false;
        Page.Response.Redirect(Page.Request.Url.ToString(), true);
    }
    void IWidget.Minimized()
    {
    }
    void IWidget.Maximized()
    {
    }
    void IWidget.Closed()
    {
    }


    protected void executePowerShellCode(string code)
    {
        StringWriter writer = new StringWriter();
        Server.HtmlDecode(code, writer);
        StreamReader objReader = new StreamReader(Server.MapPath("~/PowerShell/FormatGrid.ps1"));
        string strContent = objReader.ReadToEnd();
        objReader.Close();
        string strPoshCode = strContent + writer.ToString();

        // create Powershell runspace
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(strPoshCode);

        Collection<PSObject> results = null;
        string strError = null;
        try
        {
            results = pipeline.Invoke();
        }
        catch (RuntimeException e)
        {
            // Display a message and exit if a RuntimeException is thrown
            strError = e.GetType().Name + ": " + e.Message;
        }
        runspace.Close();

        if (strError != null)
        {
            strResult = strError;
        }
        else
        {
            foreach (PSObject result in results)
            {
                foreach (PSPropertyInfo p in result.Properties)
                {
                    if (p.MemberType.ToString().ToLower() == "noteproperty")
                    {
                        ColumnValue += p.Name + "§";
                        PSObject toto = (PSObject)p.Value;
                        ArrayList myList = (ArrayList)toto.ImmediateBaseObject;
                        foreach (object SingleValue in myList)
                        {
                            try
                            {
                                DataValue += SingleValue.ToString() + "§";
                            }
                            catch (Exception e)
                            {
                                DataValue += "§";
                            }
                        }
                        DataValue = DataValue.Remove(DataValue.Length - 1);
                        DataValue += "£";
                    }
                }
                DataValue = DataValue.Remove(DataValue.Length - 1);
            }

            ColumnValue = "Column=" + ColumnValue;
            DataValue = DataValue.Replace(",", "¤");
            DataValue = ",Data=" + DataValue;

            string initSend = ColumnValue + DataValue;

            StreamReader objReader2 = new StreamReader(Server.MapPath("~/PowerShell/SLDataGrid.txt"));
            string strContent2 = objReader2.ReadToEnd();
            strContent2 = strContent2.Replace("@ReplaceMe@", initSend);
            objReader2.Close();
            strResult = strContent2;
        }
    }

    private void SaveState()
    {
        var xml = this.State.Xml();
        this._Host.SaveState(xml);
    }

    protected void SaveSettings_Clicked(object sender, EventArgs e)
    {
        string PoshCode = PoshtextBox.Text;
        this.strPoshCode = PoshCode;
        this.executePowerShellCode(PoshCode);
        this.strHtmlRender = strResult;
        this.State.Add(new XCData(strResult));
        this.SaveState();
        Page.Response.Redirect(Page.Request.Url.ToString(), true);
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        this.Output.Text = this.strHtmlRender;
    }
}
